package com.huangliusong.threadcurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author huangliusong
 * @since 2018/11/21
 * {@link }
 */
@Slf4j
public class SeamphoreExample2 {
    private static int threadCount=20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService=Executors.newCachedThreadPool();
        final Semaphore semaphore=new Semaphore(3) ;
        for (int i=0;i<threadCount;i++){
            final int threadNum=i;
            executorService.execute(()->{
                try {
                    if (semaphore.tryAcquire()){
                        test31(threadNum);
                        semaphore.release(3);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("{}",e);
                }
            });
        }

        log.info("finish");
        executorService.shutdown();
    }


    private static void test31(int threadNum) throws  Exception{

        log.info("{}",threadNum);
        Thread.sleep(1000);
    }
}
